package com.huilian.iotbox.data.utils;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * Crc16 CCITT-False
 * @author chenqiwen
 * @CreateDate: 2021-05-08-16-07
 * @Description:
 */
public class Crc16CCITTFalseUtil {

    public static void main(String[] args) {
        String str = "8003F0EF00";

        System.out.println(Crc16CCITTFalseUtil.crc_16_CCITT_False_Retrun_hex(str));
    }


    static int crc = 0xffff; // initial value
    //        static int polynomial = 0x1021; // poly value
    static int polynomial = 0x8005; // poly value


    private static void init(){
        crc = 0xffff;
        polynomial = 0x8005;
    }
    /**
     * 为Byte数组最后添加两位CRC校验
     *
     * @param buf（验证的byte数组）
     * @return
     */
    public static byte[] setParamCRC(byte[] buf) {
        int checkCode = 0;
        checkCode = crc_16_CCITT_False_Retrun_Decimal(buf);
        byte[] crcByte = new byte[2];
        crcByte[0] = (byte) ((checkCode >> 8) & 0xff);
        crcByte[1] = (byte) (checkCode & 0xff);
        // 将新生成的byte数组添加到原数据结尾并返回
        return concatAll(buf, crcByte);
    }

    /**
     * 返回10进制的校验码
     * CRC-16/CCITT-FALSE x16+x12+x5+1 算法
     *
     * info
     * Name:CRC-16/CCITT-FAI
     * Width:16
     * RefIn:False
     * RefOut:False
     * XorOut:0x0000
     *
     * @param bytes
     * @return
     */
    private static int crc_16_CCITT_False_Retrun_Decimal(byte[] bytes) {

        for (int index = 0; index < bytes.length; index++) {
            byte b = bytes[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit) {
                    crc ^= polynomial;
                }
            }
        }
        int crc_copy = crc;
        crc_copy &= 0xffff;
        init();
        return crc_copy;
    }



    /**
     * CRC-16/CCITT-FALSE x16+x12+x5+1 算法
     *
     * info
     * Name:CRC-16/CCITT-FAI
     * Width:16
     * RefIn:False
     * RefOut:False
     * XorOut:0x0000
     *
     * @param hex
     * @return
     */
    public static String crc_16_CCITT_False_Retrun_hex(String hex) {
        byte[] bytes = hexStr2Byte(hex);
        for (int index = 0; index < bytes.length; index++) {
            byte b = bytes[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit) {
                    crc ^= polynomial;
                }
            }
        }
        crc &= 0xffff;

        //输出String字样的16进制
        String strCrc = Integer.toHexString(crc).toUpperCase();
        if (strCrc.length() == 2) {
            strCrc = "00" + strCrc;
        } else if (strCrc.length() == 3) {
            strCrc = "0" + strCrc;
        }
        strCrc = strCrc.substring(2, 4) + strCrc.substring(0, 2);

        init();
        return strCrc.toUpperCase();
    }


    /**
     * 将字符串转为字节数组
     * @param hex
     * @return
     */
    public static byte[] hexStr2Byte(String hex) {
        ByteBuffer bf = ByteBuffer.allocate(hex.length() / 2);
        for (int i = 0; i < hex.length(); i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            bf.put(b);
        }
        return bf.array();
    }


    /***
     * CRC校验是否通过
     *
     * @param srcByte
     * @param length(验证码字节长度)
     * @return
     */
    public static boolean isPassCRC(byte[] srcByte, int length) {

        // 取出除crc校验位的其他数组，进行计算，得到CRC校验结果
        int calcCRC = calcCRC(srcByte, 0, srcByte.length - length);
        byte[] bytes = new byte[2];
        bytes[0] = (byte) ((calcCRC >> 8) & 0xff);
        bytes[1] = (byte) (calcCRC & 0xff);

        // 取出CRC校验位，进行计算
        int i = srcByte.length;
        byte[] b = { srcByte[i - 2] ,srcByte[i - 1] };

        // 比较
        return bytes[0] == b[0] && bytes[1] == b[1];
    }

    /**
     * 对buf中offset以前crcLen长度的字节作crc校验，返回校验结果
     * @param  buf
     * @param crcLen
     */
    private static int calcCRC(byte[] buf, int offset, int crcLen) {
        int start = offset;
        int end = offset + crcLen;
        for (int index = start; index < end; index++) {
            byte b = buf[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit) {
                    crc ^= polynomial;
                }
            }
        }
        int crc_copy = crc;
        crc_copy &= 0xffff;
        init();
        return crc_copy;
    }

    /**
     * 多个数组合并
     *
     * @param first
     * @param rest
     * @return
     */
    public static byte[] concatAll(byte[] first, byte[]... rest) {
        int totalLength = first.length;
        for (byte[] array : rest) {
            totalLength += array.length;
        }
        byte[] result = Arrays.copyOf(first, totalLength);
        int offset = first.length;
        for (byte[] array : rest) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }
        return result;
    }
}
